<template>
  <div id="add_goods">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 警告 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        align-center
        finish-status="success"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 标签页 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'left'"
          style="height: 100%"
          :before-leave="tabsBefore"
          @tab-click="tabsClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="getAddList"
                :props="addProps"
                @change="handleChange"
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染商品参数表单 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyData"
              :key="manyData.attr_id"
            >
              <!-- 渲染复选框 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="itemSon"
                  border
                  v-for="(itemSon, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染商品参数表单 -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyData"
              :key="onlyData.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="imgSrc"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture-card"
              :headers="headerObj"
              :on-success="imgSuccess"
            >
              <i slot="default" class="el-icon-plus"></i>
            </el-upload>
            <el-dialog title="图片预览" :visible.sync="imgVisible">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <el-button type="primary" class="btnAdd" @click="addInfos"
              ><span>添加商品</span></el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'add',
  data() {
    // 商品价格校验
    const addPrice = (rule, value, callback) => {
      let reg = /^[1-9]*[1-9][0-9-.]*$/
      if (!reg.test(value)) {
        callback(new Error('商品价格必须是大于0的整数或小数'))
      }
    }
    // 商品重量校验
    const addWeight = (rule, value, callback) => {
      let reg = /^[1-9]*[1-9][0-9-.]*$/
      if (!reg.test(value)) {
        callback(new Error('商品重量必须是大于0的整数或小数'))
      }
    }
    // 商品数量校验
    const addNumber = (rule, value, callback) => {
      let reg = /^[1-9]*[1-9][0-9]*$/
      if (!reg.test(value)) {
        callback(new Error('商品数量必须是大于0的整数'))
      }
    }
    return {
      // 步骤条切换索引号
      activeIndex: '0',
      // 添加表单数据
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: [],
      },
      // 表单验证
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: addPrice, trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { validator: addWeight, trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { validator: addNumber, trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' },
        ],
      },
      // 商品分类数据列表
      getAddList: [],
      // 级联选择器 :props配置
      addProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 商品动态参数数据
      manyData: [],
      // 商品静态属性数据
      onlyData: [],
      // 图片上传地址
      imgSrc: 'http://127.0.0.1:8888/api/private/v1/upload',
      dialogImageUrl: '',
      imgVisible: false,
      // 图片上传时的请求头部
      headerObj: {
        Authorization: window.sessionStorage.getItem('token'),
      },
    }
  },
  created() {
    this.getAddInfo()
  },
  methods: {
    async getAddInfo() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return
      this.getAddList = res.data
      // console.log(this.getAddList)
    },
    // 监听级联选择器值得变化
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.$message.warning('只能选择三级商品分类')
        this.addForm.goods_cat = []
        return
      }
      // 如果该数组等于3
      // console.log(this.addForm.goods_cat[2]);
    },
    // 切换标签页
    tabsBefore(activeName, oldActiveName) {
      if (oldActiveName == 0 && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // 切换标签页触发
    async tabsClicked() {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(
          `categories/${this.caseId}/attributes`,
          {
            params: {
              sel: 'many',
            },
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach((item) => {
          // 记住：split() 是把字符串以什么样的字符为界限，分割成数组的形式
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyData = res.data //商品动态参数数据
        // console.log(this.manyData)
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.caseId}/attributes`,
          {
            params: {
              sel: 'only',
            },
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.onlyData = res.data //商品静态属性数据
        // console.log(this.onlyData)
      }
    },
    // 点击删除触发
    handleRemove(file) {
      //即将要删除的临时路径
      let fileTmpPath = file.response.data.tmp_path
      // 拿到要删除那一项的索引号
      const index = this.addForm.pics.findIndex(
        (item) => item.pic === fileTmpPath
      )
      //从添加数据商品列表中删除
      this.addForm.pics.splice(index, 1)
      console.log(this.addForm)
    },
    // 点击查看大图触发
    handlePreview(file) {
      this.dialogImageUrl = file.response.data.url
      this.imgVisible = true
    },
    // 图片上传成功时触发
    imgSuccess(response) {
      console.log(response)
      // 把临时路径保存到添加数据列表中-> this.addForm.pics
      const pinInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(pinInfo)
      console.log(this.addForm)
    },
    // 商品添加
    async addInfos() {
      let addFlag = false
      this.$refs.addFormRef.validate((vail) => {
        if (!vail) {
          //如果表单验证失败
          addFlag = true
          return this.$message.error('请完善商品信息的必填项再添加商品！')
        }
      })
      if (addFlag) {
        return
      } else {
        // 深拷贝一份addForm
        const newForm = _.cloneDeep(this.addForm)
        newForm.goods_cat = newForm.goods_cat.join(',')
        const { data: res } = await this.$http.post('goods', newForm)
        if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('添加商品成功')
        this.$router.push('/goods')
      }
    },
  },
  computed: {
    // 获取第三级别的分类id值
    caseId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    },
  },
}
</script>

<style lang="less" scoped>
.el-card {
  margin-top: 15px;
  box-shadow: none !important;
}
.el-steps {
  margin: 20px 0;
}
/deep/ .el-step__title,
/deep/ .el-step__icon-inner {
  font-size: 12px;
}
.el-checkbox {
  margin: 0 10px 10px 0 !important;
  font-size: 12px !important;
}
/deep/.el-checkbox__input.is-checked + .el-checkbox__label {
  font-size: 12px !important;
}
.btnAdd {
  margin-top: 15px;
}
</style>